<template>
  <div class="app-container app-containerrole app-containerMoneytabel">
    <div class="filter-container">
        <el-input size="small" @keyup.enter.native="handleFilter" placeholder="请输入角色名称" style="width: 200px;" class="filter-item"  v-model="listQuery.roleName">
        </el-input>
        <el-button size="small" class="filter-item filter-itemBut" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button size="small" class="filter-item filter-itemBut" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
      </div>
      <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column label="角色名称"  align="center">
          <template slot-scope="scope">
            {{scope.row.zh}}
          </template>
        </el-table-column>
        <el-table-column label="角色编码"  align="center">
          <template slot-scope="scope">
            {{scope.row.name}}
          </template>
        </el-table-column>
        <el-table-column label="描述"  align="center">
          <template slot-scope="scope">
            {{scope.row.remark}}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="created_at" label="添加时间" width="200">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span v-if="scope.row.createTime">{{scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
          </template>
        </el-table-column>
      
        <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" v-if="scope.row.name!=='ROLE_ADMIN'" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" v-if="scope.row.name!=='ROLE_ADMIN'" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table> 
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
          :page-sizes="[10,20,30, 50]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>

    <!--新增修改弹出层-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" >
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="80px" style='width: calc(100% - 100px); margin-left:50px;; margin-right:50px'>
        <el-input v-model="temp.id" v-show="false"></el-input>
        <el-form-item label="角色名称" prop="zh">
          <el-input size="small" v-model="temp.zh"></el-input>
        </el-form-item>
        <el-form-item label="角色编码" prop="name">
          <el-input size="small" v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input size="small" v-model="temp.remark"></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="resourcesIds">
          <resources-tree ref="resourcesTree" v-model="resourcesIds"  :resourcesIds="resourcesIds" ></resources-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">提交</el-button>
        <el-button v-else type="primary" @click="updateData">更新</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  queryPage,
  saveOrUpdate,
  deleteById,
  bindResources,
  getBindResources
} from "@/api/role";
import ResourcesTree from "../components/ResourcesTree";
export default {
  components: {
    ResourcesTree
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 10,
        roleName: null,
        sort: "+id"
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "更新",
        create: "添加"
      },
      resourcesIds: [],
      temp: {
        id: null,
        name: null,
        zh: null,
        resourcesIds: [],
        remark: null
      },
      rules: {
        zh: [
          { required: true, message: "请输入角色中文名称", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入角色编码", trigger: "blur" }
        ],
        resourcesIds: [
          { required: true, message: "请选择权限", trigger: "change" }
        ]
      }
    };
  },
  mounted: function() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      queryPage(this.listQuery).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
      this.listLoading = false;
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.fetchData();
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.fetchData();
    },
    handleCreate() {
      this.resetTemp();
      if (this.$refs.resourcesTree) {
        this.$refs.resourcesTree.setCheckedKeys([]);
      }
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.temp.resourcesIds = this.resourcesIds
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          saveOrUpdate(this.temp).then(() => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      let self = this
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
        setTimeout(()=>{
          //资源回传
          getBindResources(self.temp.name).then(response => {
            self.$refs.resourcesTree.setCheckedKeys(response.data);
            self.resourcesIds = response.data;
          });
        },100)
      });
    },
    updateData() {
      this.temp.resourcesIds = this.resourcesIds
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          saveOrUpdate(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v);
                this.list.splice(index, 1, this.temp);
                break;
              }
            }
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleDelete(row) {
      const loading = this.$loading({
        lock: true,
        text: "提交中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      setTimeout(() => {
        loading.close();
      }, 800);
      this.$confirm("删除后不可恢复, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteById(row.id).then(() => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000
        });
        const index = this.list.indexOf(row);
        this.list.splice(index, 1);
      });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消"
        });
      });
    },
    resetTemp() {
      this.temp = {
        id: null,
        name: null,
        zh: null,
        resourcesIds: [],
        remark: null
      };
    }
  }
};
</script>


<style scoped>
.app-containerrole .el-input {
  min-width: 50px;
}
.filter-container {
  margin-bottom: 20px;
  overflow: hidden;
}

.pagination-container {
  margin-top: 25px;
  overflow: hidden;
  display: flex;
  justify-content: flex-end;
}

.filter-itemBut {
  margin-left: 25px;
}
</style>
